<?php

namespace App\Http\Controllers;

use App\Services\GitService;
use Illuminate\Http\Request;

class GitController extends Controller
{
    /**
     * 检查是否是git仓库
     * @param Request $i
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkGitProject(Request $i) {
        $name = $i->input('name');
        $user = $i->input('user');

        $projectName = $user.'-'.$name;
        $isGitProject = GitService::isGitProject($projectName);
        $url = self::getCloneUrl($projectName);
        if ($isGitProject) {
            return self::success(['isGit' => 1, 'url' => $url]);
        } else {
            return self::success(['isGit' => 0, 'url' => $url]);
        }
    }

    /**
     * 创建GIT仓库
     * @param Request $i
     * @return \Illuminate\Http\JsonResponse
     * @throws \CzProject\GitPhp\GitException
     */
    public function createGitProject(Request $i) {
        $name = $i->input('name');
        $user = $i->input('user');
        $project = $user.'-'.$name;
        $gitService = new GitService($project);
        $gitService->createRepository();
        $gitUrl = self::getCloneUrl($project);
        return self::success(['url' => $gitUrl]);
    }

    static function getCloneUrl($project) {
        $path = GitService::getRootPath($project);
        return "file:///".$path;
    }
}
